<template>
  <!-- 手机验证码登录 -->
  <div class="mobile-login box-border">
    <div>
      <div  v-if="store.toggle">
        <YuInput
            ref="yuInput"
            v-for="(d, i) in descInput"
            :key="d.title"
            :title="d.title"
            v-model:value="dataInput[i]"
            :maxlength="d.maxlength"
            :rules="d.rules"
            width="18rem"
        >
          <template v-slot:yuSlot v-if="d.btn">
            <YuButton v-if="userInfo.isCode === 0" title="发送验证码" @click="getCode">
              发送验证码
            </YuButton>
            <div v-else-if="userInfo.isCode === 1">请稍等</div>
            <div v-else-if="userInfo.isCode === 2">{{ userInfo.time }}s</div>
          </template>
        </YuInput>
        <YuButton title="登录" padding="5px 20px" @click="login" />
      </div>
      <QrCode v-else />
      <div class="switchover flex yu-titleColor items-center justify-center mt-4 text-xl" @click="toggleLogin">
        <span class="i-mdi-swap-horizontal"/>
        <span>切换登录方式</span>
      </div>
    </div>

  </div>
</template>

<script setup>
import {useRouter} from "vue-router";
import {onMounted, onUnmounted, reactive, ref, toRefs} from "vue"
import YuInput from '@/components/YuInput/index.vue'
import YuButton from '@/components/YuButton/index.vue'

import {useStore} from "@/store/index"
import {Notify} from "vant";
import {inject} from 'vue'
import QrCode from '@/components/QrCode/index.vue'

const store = useStore()
const router = useRouter()

onMounted(() => {
  // 进入页面不允许展示头部导航
  // store.isShowMobileSearch = false
})
onUnmounted(() => {
  // 离开页面允许展示头部导航
  // store.isShowMobileSearch = true
})
const yuInput = ref(null)
// 登录成功刷新页面
const reload = inject('reload')

// 手机号格式
const phoneRule = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/


// 手机号和验证码
const userInfo = reactive({
  dataInput: {
    yuPhone: null,
    yuCode: null
  },
  descInput: {
    yuPhone: {
      inputType: 'number',
      title: '手机号',
      maxlength: 11,
      rules: [
        {pattern: phoneRule, message: '手机号格式不对'}
      ]
    },
    yuCode: {
      inputType: 'number',
      title: '验证码',
      btn: true,
      maxlength: 4,
      rules: [{ pattern: /\d{4}/ , message: '验证码长度不够' }]
    }
  },
  time: 60, // 倒计时
  isCode: 0 // 判断是否发送了验证码 0：未发送，1：发送中， 2： 发送成功
})

// 登录
const login = () => {
  // 遍历所有的登录框数据是否校验成功不成功的会返回true，成功的会返回false，都存到数组中
  let arr = yuInput.value.map(item => {
    return item.rulesFn()
  })
  // 如果返回的值都是false也就是表单校验通过可以进行下一步处理
  if (!arr.includes(true)) {
    // params: { phone,captcha }
    // 调用验证手机号和验证码是否匹配,如果匹配在登录
    let params = { phone: userInfo.dataInput.yuPhone.trim(), captcha: userInfo.dataInput.yuCode.trim() }
    store.getCaptchaVerify(params).then(res => {
      if (Number(res.code) === 200) {
        router.push('/')
        // 刷新页面
        reload()
      }
    })
  }
}

// 获取验证码
const getCode = () => {
  // 手机号符合规范才允许发送验证码
  if (phoneRule.test(userInfo.dataInput.yuPhone)) {
    // 请求接口前设置为1
    userInfo.isCode = 1
    // 发送验证码
    store.getCaptchaSent(userInfo.dataInput.yuPhone).then(code => {
      if (code === 200) {
        // 发送验证码成功调为2并且设置验证码时间
        userInfo.isCode = 2
        userInfo.time = 60
        verificationCodeCountdown()
        Notify({
          background: 'blue',
          color: 'white',
          message: '发送成功'
        })
      }
    })
  } else {
    Notify({
      background: 'red',
      color: 'white',
      message: '手机号不对'
    })
  }
}

// 倒计时
const verificationCodeCountdown = () => {
  let timer = null
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    if (userInfo.time <= 0) {
      // 验证码结束设为false
      userInfo.isCode = 0
      clearInterval(timer)
    }
    --userInfo.time
  }, 1000)
}

const {phone, captcha, descInput, dataInput} = toRefs(userInfo)

// 切换登录方式
const toggleLogin = () => {
  store.toggle = !store.toggle
  if(store.toggle === false) {
    // 获取key值并且通过key,获取验证码并且，循环调用校验是否扫码确认成功，最后获取用户信息
    store.getKey()
  }
}

</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
